package com.tj.bo.account.server.services;

import com.fqgj.exception.common.ApplicationException;
import com.tj.bo.account.client.CreateAccountService;
import com.tj.bo.account.client.enums.AccountStateEnum;
import com.tj.bo.account.client.enums.AccountTypeEnum;
import com.tj.bo.account.client.vo.CreateAccountVO;
import com.tj.bo.account.server.dao.AccountDao;
import com.tj.bo.account.server.entity.AccountEntity;
import com.tj.bo.common.conf.util.SerialNumberUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/**
 * 创建账户服务
 * User: anonymous
 * Date: 2020/06/11
 * Time: 下午2:16
 */
@Service
public class CreateAccountServiceImpl implements CreateAccountService {
    public static final BigDecimal DEMO_ACCOUNT_INITIAL_AMOUNT = new BigDecimal(10000);
    @Autowired
    private AccountDao accountDao;

    @Override
    public void createAccount(CreateAccountVO createAccountVO) {
        AccountEntity oldAccountEntity = accountDao.selectByUserCode(createAccountVO.getUserCode());
        if (oldAccountEntity != null) {
            throw new ApplicationException("Account already exists");
        }
        AccountEntity accountEntity = new AccountEntity();
        accountEntity.setAccountNo(SerialNumberUtil.getBizOrderNumber("A", "C"));
        accountEntity.setAccountName("");
        accountEntity.setAccountType(createAccountVO.getAccountTypeEnum().name());
        accountEntity.setStatus(AccountStateEnum.VALID.getCode());
        accountEntity.setUserCode(createAccountVO.getUserCode());
        accountEntity.setAllowWithdrawal(createAccountVO.getAccountTypeEnum() == AccountTypeEnum.REAL ? 1 : 0);
        accountEntity.setUserName(createAccountVO.getUserName());
        accountEntity.setOperator(createAccountVO.getOperator());
        if (createAccountVO.getAccountTypeEnum() == AccountTypeEnum.DEMO) {
            accountEntity.setBalance(DEMO_ACCOUNT_INITIAL_AMOUNT);
            accountEntity.setAvailableBalance(DEMO_ACCOUNT_INITIAL_AMOUNT);
            accountEntity.setGrants(BigDecimal.ZERO);
        }
        accountDao.insert(accountEntity);
    }

}